//
//  FOExcel.m
//  AFNetworking
//
//  Created by 新庭 on 2022/3/5.
//

#import "FOExcel.h"
#import "PStorage.h"

@implementation FOExcel

- (instancetype)init
{
    self = [super init];
    if (self) {
        _body = [NSMutableArray array];
    }
    return self;
}

- (void)save {
    NSString *path = [self tempPath];
    
    lxw_workbook *workbook = workbook_new([path UTF8String]);
    lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);
    for (NSInteger i = 0; i < self.body.count; i++) {
        FOExcelLine *line = [self.body objectAtIndex:i];
        [line writeSheet:worksheet inRow:(lxw_row_t)i];
    }
    lxw_error err = workbook_close(workbook);
    NSLog(@"%u", err);
}

- (void)exportSample {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filename = [documentPath stringByAppendingPathComponent:@"c_demo.xlsx"];
    lxw_workbook *workbook = workbook_new([filename UTF8String]);
    lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);
    int row = 0;
    int col = 0;
 
    worksheet_write_string(worksheet, row, col, "Hello me!", NULL);
 
    lxw_error err = workbook_close(workbook);
    NSLog(@"%u", err);
}

- (NSString *)tempPath {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *timeStr = [NSString stringWithFormat:@"%ld.xlsx", (NSInteger)time];
    NSString *filename = [documentPath stringByAppendingPathComponent:timeStr];
    return filename;
}

@end

@implementation FOExcelContent: NSObject



@end

@implementation FOExcelNode: NSObject

+ (instancetype)nodeWithText:(NSString *)text {
    FOExcelNode *node = [[FOExcelNode alloc] init];
    if (text.length <= 0) {
        node.isBlank = YES;
    } else {
        FOExcelContent *c = [[FOExcelContent alloc] init];
        c.text = text;
        node.content = c;
    }
    return node;
}

- (void)writeSheet:(lxw_worksheet *)sheet inRow:(lxw_row_t)row atCol:(lxw_col_t)col {
    if (self.isBlank) {
        return;
    }
    worksheet_write_string(sheet, row, col, [self.content.text UTF8String], NULL);
}

@end

@implementation FOExcelLine: NSObject

+ (instancetype)lineWithTexts:(NSArray<NSString *> *)texts {
    FOExcelLine *line = [[FOExcelLine alloc] init];
    for (NSString *text in texts) {
        [line.nodes addObject:[FOExcelNode nodeWithText:text]];
    }
    return line;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _nodes = [NSMutableArray array];
    }
    return self;
}

- (void)writeSheet:(lxw_worksheet *)sheet inRow:(lxw_row_t)row {
    for (lxw_col_t i = 0; i < self.nodes.count; i++) {
        FOExcelNode *node = [self.nodes objectAtIndex:i];
        [node writeSheet:sheet inRow:row atCol:i];
    }
}

@end
